In [1]:
import decimal
In [2]:
ctx = decimal.getcontext()
In [3]:
ctx.prec = 40
In [4]:
one_third = decimal.Decimal('1') / decimal.Decimal('3')
In [5]:
one_third
Out[5]:
In [6]:
one_third == +one_third
Out[6]:
In [7]:
ctx.prec = 28
In [8]:
one_third == +one_third
Out[8]:
In [9]:
+one_third
Out[9]:
In [10]:
from collections import Counter
In [11]:
ct = Counter('abracadabra')
In [12]:
ct
Out[12]:
In [14]:
ct['r'] = -3
In [15]:
ct['d'] = 0
In [16]:
ct
Out[16]:
In [18]:
+ct
Out[18]:
In [1]:
from array import array
import reprlib
import math
import numbers
import functools
import operator
import itertools
class Vector:
typecode = 'd'
def __init__(self, components):
self._components = array(self.typecode, components)
def __iter__(self):
return iter(self._components)
def __repr__(self):
components = reprlib.repr(self._components)
components = components[components.find('['):-1]
return 'Vector({})'.format(components)
def __str__(self):
return str(tuple(self))
def __bytes__(self):
return (bytes([ord(self.typecode)]) +
bytes(self._components))
def __eq__(self, other):
if isinstance(other, Vector):
return (len(self) == len(other) and
all(a == b for a, b in zip(self, other)))
else:
return NotImplemented
def __hash__(self):
hashes = (hash(x) for x in self._components)
return functools.reduce(operator.xor, hashes, 0)
def __abs__(self):
return math.sqrt(sum(x * x) for x in self)
def __neg__(self):
return Vector(-x for x in self)
def __pos__(self):
return Vector(self)
def __add__(self, other):
try:
pairs = itertools.zip_longest(self, other, fillvalue=0.0)
return Vector(a + b for a, b in pairs)
except TypeError:
return NotImplemented
def __radd__(self, other):
return self + other
def __mul__(self, scalar):
if isinstance(scalar, numbers.Real):
return Vector(n * scalar for n in self)
else:
return NotImplemented
def __rmul__(self, scalar):
return self * scalar
def __matmul__(self, other):
try:
return sum(a * b for a, b in zip(self, other))
except TypeError:
return NotImplemented
def __rmatmul__(self, other):
return self @ other
def __bool__(self):
return bool(abs(self))
def __len__(self):
return len(self._components)
def __getitem__(self, index):
cls = type(self)
if isinstance(index, slice):
return cls(self._components[index])
elif isinstance(index, numbers.Integral):
return self._components[index]
else:
msg = '{.__name__} indices must be integers'
raise TypeError(msg.format(cls))
shortcut_names = 'xyzt'
def __getattr__(self, name):
cls = type(self)
if len(name) == 1:
pos = cls.shortcut_names.find(name)
if 0 <= pos < len(self._components):
return self._components[pos]
msg = '{.__name__!r} object has no atttribute {!r}'
raise AttributeError(msg.format(cls, name))
def __setattr__(self, name, value):
cls = type(self)
if len(name) == 1:
if name in cls.shortcut_names:
error = 'readonly attribute {attr_name!r}'
elif name.islower():
error = "can't set attributes 'a' to 'z' in {cls_name!r}"
else:
error = ''
if error:
msg = error.format(cls_name=cls.__name__, attr_name=name)
raise AttributeError(msg)
super().__setattr__(name, value)
def angle(self, n):
r = math.sqrt(sum(x * x for x in self[n:]))
a = math.atan2(r, self[n-1])
if (n == len(self) - 1) and (self[-1] < 0):
return math.pi * 2 - a
else:
return a
def angles(self):
return (self.angle(n) for n in range(1, len(self)))
def __format__(self, fmt_spec=''):
if fmt_spec.endswith('h'): # hyperspherical coordinates
fmt_spec = fmt_spec[:-1]
coords = itertools.chain([abs(self)], self.angles())
outer_fmt = '<{}>'
else:
coords = self
outer_fmt = '({})'
components = (format(c, fmt_spec) for c in coords)
return outer_fmt.format(', '.join(components))
@classmethod
def frombytes(cls, octets):
typecode = chr(octets[0])
memv = memoryview(octets[1:]).cast(typecode)
return cls(memv)
In [13]:
v1 = Vector([3, 4, 5])
v2 = Vector([6, 7, 8])
v1 + v2
Out[13]:
In [14]:
v1 + v2 == Vector([3+6, 4+7, 5+8])
Out[14]:
In [15]:
v1 + (10, 20, 30)
Out[15]:
In [16]:
from vector2d_v3 import Vector2d
In [17]:
v2d = Vector2d(1, 2)
In [18]:
v1 + v2d
Out[18]:
In [19]:
(10, 20, 30) + v1
Out[19]:
In [20]:
v2d + v1
Out[20]:
In [21]:
v1 + 1
In [22]:
v1 + 'ABC'
In [28]:
v1 = Vector([1, 2, 3])
In [29]:
v1 * 10
Out[29]:
In [31]:
v1 = Vector([1.0, 2.0, 3.0])
In [32]:
14 * v1
Out[32]:
In [33]:
v1 * True
Out[33]:
In [34]:
from fractions import Fraction
In [35]:
v1 * Fraction(1, 3)
Out[35]:
In [2]:
va = Vector([1, 2, 3])
vz = Vector([5, 6, 7])
In [4]:
va @ vz == 38.0
Out[4]:
In [5]:
[10, 20, 30] @ vz
Out[5]:
In [6]:
va @ 3
In [8]:
va = Vector([1.0, 2.0, 3.0])
vb = Vector(range(1, 4))
va == vb
Out[8]:
In [9]:
vc = Vector([1, 2])
from vector2d_v3 import Vector2d
v2d = Vector2d(1, 2)
vc == v2d
Out[9]:
In [10]:
t3 = (1, 2, 3)
va == t3
Out[10]:
In [11]:
va != vb
Out[11]:
In [12]:
vc != v2d
Out[12]:
In [13]:
va != (1, 2, 3)
Out[13]:
In [2]:
v1 = Vector([1, 2, 3])
In [3]:
v1_alias = v1
In [5]:
id(v1)
Out[5]:
In [6]:
v1 += Vector([4, 5, 6])
In [7]:
v1
Out[7]:
In [8]:
id(v1)
Out[8]:
In [9]:
v1_alias
Out[9]:
In [10]:
v1 *= 11
In [11]:
v1
Out[11]:
In [12]:
id(v1)
Out[12]:
In [14]:
import abc
class Tombola(abc.ABC):
@abc.abstractmethod
def load(self, iterable):
"""Add items from an iterable"""
@abc.abstractmethod
def pick(self):
"""Remove item at random, returning it
This method should raise 'LookupError' when the instance is empty.
"""
def loaded(self):
"""Return 'True' if there's at least 1 item, 'False' otherwise."""
return bool(self.inspect())
def inspect(self):
"""Return a sorted tuple with the items currently inside."""
items = []
while True:
try:
items.append(self.pick())
except LookupError:
break
self.load(items)
return tuple(sorted(items))
In [15]:
import random
class BingoCage(Tombola):
def __init__(self, items):
self._randomizer = random.SystemRandom()
self._items = []
self.load(items)
def load(self, items):
self._items.extend(items)
self._randomizer.shuffle(self._items)
def pick(self):
try:
return self._items.pop()
except IndexError:
raise LookupError('pick from empty BingoCage')
def __call__(self):
self.pick()
In [16]:
import itertools
class AddableBingoCage(BingoCage):
def __add__(self, other):
if isinstance(other, Tombola):
return AddableBingoCage(self.inspect() + other.inspect())
else:
return NotImplemented
def __iadd__(self, other):
if isinstance(other, Tombola):
other_iterable = other.inspect()
else:
try:
other_iterable = iter(other)
except TypeError:
self_cls = type(self).__name__
msg = "right operand in += must be {!r} or an iterable"
raise TypeError(msg.format(self_cls))
self.load(other_iterable)
return self
In [17]:
vowels = 'AEIOU'
globe = AddableBingoCage(vowels)
globe.inspect()
Out[17]:
In [18]:
globe.pick() in vowels
Out[18]:
In [19]:
len(globe.inspect())
Out[19]:
In [20]:
globe2 = AddableBingoCage('XYZ')
globe3 = globe + globe2
In [21]:
len(globe3.inspect())
Out[21]:
In [22]:
void = globe + [10, 20]
In [23]:
globe_orig = globe
len(globe.inspect())
Out[23]:
In [24]:
globe += globe2
len(globe.inspect())
Out[24]:
In [25]:
globe += ['M','N']
len(globe.inspect())
Out[25]:
In [26]:
globe is globe_orig
Out[26]:
In [27]:
globe += 1
In [ ]: